const ChatHandler = require('./chatHandler');
const DataHandler = require('./dataHandler');
const NotificationHandler = require('./notificationHandler');
const BroadcastManager = require('./broadcast');
const WebSocketUtils = require('./utils');

function setupAdvancedWebSocketServer(server) {
    const wsServers = new Map();
    const broadcastManager = new BroadcastManager();

    // 初始化各个服务处理器
    const chatHandler = new ChatHandler();
    const dataHandler = new DataHandler();
    const notificationHandler = new NotificationHandler();

    // 注册服务器
    wsServers.set('/ws/chat', chatHandler.getServer());
    wsServers.set('/ws/data', dataHandler.getServer());
    wsServers.set('/ws/notifications', notificationHandler.getServer());

    // 注册到广播管理器
    broadcastManager.registerServer('/ws/chat', chatHandler.getServer());
    broadcastManager.registerServer('/ws/data', dataHandler.getServer());
    broadcastManager.registerServer('/ws/notifications', notificationHandler.getServer());

    // 处理HTTP升级请求
    server.on('upgrade', (request, socket, head) => {
        const pathname = new URL(request.url, `http://${request.headers.host}`).pathname;
        console.log('WebSocket升级请求路径:', pathname);

        const wss = wsServers.get(pathname);
        if (wss) {
            wss.handleUpgrade(request, socket, head, (ws) => {
                console.log("协议升级成功");
                WebSocketUtils.setupConnectionLogging(ws, wss);
                wss.emit('connection', ws, request);
            });
        } else {
            console.log("路径不匹配，关闭连接");
            socket.destroy();
        }
    });

    // 返回所有WebSocket服务器实例和工具函数
    return {
        wsServers,
        chatWss: chatHandler.getServer(),
        dataWss: dataHandler.getServer(),
        notificationWss: notificationHandler.getServer(),
        broadcast: (wssName, data, filter) => {
            broadcastManager.broadcast(wssName, data, filter);
        },
        broadcastToAll: (data, filter) => {
            broadcastManager.broadcastToAll(data, filter);
        },
        getStats: () => {
            return broadcastManager.getServerStats();
        },
        getConnectedClients: (path) => {
            return broadcastManager.getConnectedClients(path);
        }
    };
}

module.exports = setupAdvancedWebSocketServer;